#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#include "node.h"

#define FILE_NAME "Nodes.dat"

void verify_args(int, char **);
void sighandler(int);
void child(void);
void parent(int, char **);

//enum { INPUT, OUTPUT, PIPE };

static int allowed = 0;
//static int pipefd[PIPE];

int main(int argc, char *argv[])
{
    verify_args(argc, argv);

    int cpid = fork();
    switch (cpid)
    {
        case 0:
            child();
            break;
        case -1:
            perror("fork");
            return 1;
        default:
            parent(cpid, argv);
    }

    int cstatus;
    wait(&cstatus);
    if (WEXITSTATUS(cstatus))
    {
        fprintf(stderr, "ERROR: child %d exited with code %d\n", cpid, WEXITSTATUS(cstatus));
        return 1;
    }


    return 0;
}

void verify_args(int argc, char **argv)
{
    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s <ip> <mac>\n", *argv);
        exit(EXIT_FAILURE);
    }
}

void child_handler(int sig)
{
    switch (sig)
    {
        case SIGUSR1:
            allowed = 1;
            break;
        case SIGINT:
            _exit(0);
        default:
            return;
    }
}

void parent_handler(int sig)
{
    if (sig == SIGUSR1)
        allowed = 1;
}

void child(void)
{
    signal(SIGUSR1, child_handler);
    allowed = 0;
    signal(SIGINT, child_handler);
    //Stop until parent sends signal
    while (!allowed);

    Node *p_first = NULL;
    p_first = node_read(FILE_NAME);
    node_display(p_first);

    kill(getppid(), SIGUSR1);
    while(1);
}

void parent(int cpid, char **argv)
{
    signal(SIGUSR1, parent_handler);
    usleep(1);
    kill(cpid, SIGUSR1);
    while (!allowed);

    Node *p_first = node_read(FILE_NAME);
    Node *p_node = node_new(argv[1], argv[2]);
    p_first = node_add(p_first, p_node);
    node_display(p_first);
    node_save(p_first, FILE_NAME);
    node_destroy(p_first);

    kill(cpid, SIGKILL);
}
